package net.qhzw.vip.qiyu.service;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.entity.DtsCarRental;
import net.qhzw.vip.qiyu.entity.DtsUser;
import net.qhzw.vip.qiyu.entity.DtsUserBill;
import net.qhzw.vip.qiyu.entity.SysUserTopupOrder;
import net.qhzw.vip.qiyu.handler.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import net.qhzw.vip.qiyu.util.SecurityUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class MemberWalletService {

    @Autowired
    private DtsUserService dtsUserService;

    @Autowired
    private DtsUserBillService dtsUserBillService;

    @Autowired
    private SysUserTopupOrderService userTopupOrderService;

    @Autowired
    private DtsCarRentalService dtsCarRentalService;


    /***
     * 表格导入充值
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<String> importRecharge(MultipartFile file, Long shopId) {
        log.info("【表格导入充值,文件名称】: [{}]", file.getOriginalFilename());
        ImportParams params = new ImportParams();
        //params.setTitleRows(1);//设置一级标题行为1行
        //params.setHeadRows(1);//设置header标题为1行
        List<DtsUser> dtsUserList = null;
        try {
            dtsUserList = ExcelImportUtil.importExcel(file.getInputStream(), DtsUser.class, params);
            log.info("【导入总数为】: [{}]", dtsUserList.size());
            if (!CollectionUtils.isEmpty(dtsUserList)){
                dtsUserList.forEach(data -> data.setIdCard(data.getIdCard().trim()));
            }
        } catch (Exception e) {
            log.error("【表格导入充值失败】：", JSON.toJSONString(e, true));
            throw new MyException("表格导入充值失败");
        }
        return recharge(dtsUserList, shopId);
    }


    /***
     * 用户余额充值
     * @param dtsUserList
     * @return
     */
    private List<String> recharge(List<DtsUser> dtsUserList, Long shopId) {
        List<String> cantMatch = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dtsUserList)) {
            List<String> match = new ArrayList<>();
            cantMatch = dtsUserList.stream().map(DtsUser::getIdCard).collect(Collectors.toList());
            //根据身份证号查询用户
            List<DtsUser> dtsUserDBs = dtsUserService.list(new LambdaQueryWrapper<DtsUser>()
                    .in(DtsUser::getIdCard, cantMatch));
            List<DtsUser> insertDtsUsers = new ArrayList<>();
            List<DtsUserBill> dtsUserBills = new ArrayList<>();
            List<SysUserTopupOrder> userTopupOrders = new ArrayList<>();
            //对比身份证号
            for (DtsUser dtsUserDB : dtsUserDBs) {
                for (DtsUser dtsUser : dtsUserList) {
                    if (dtsUser.getIdCard().equals(dtsUserDB.getIdCard())) {
                        //身份证号匹配上的
                        DtsUser insDtsUser = new DtsUser();
                        insDtsUser.setId(dtsUserDB.getId());
                        insDtsUser.setIdCard(dtsUser.getIdCard());
                        insDtsUser.setBalance(dtsUserDB.getBalance().add(dtsUser.getBalance()));
                        insertDtsUsers.add(insDtsUser);
                        match.add(dtsUser.getIdCard());
                        //用户账单表
                        DtsUserBill dtsUserBill = initDtsUserBill(dtsUserDB.getId(), dtsUser.getBalance(), (byte) 1, dtsUser.getRemake());
                        dtsUserBills.add(dtsUserBill);
                        //充值表
                        SysUserTopupOrder userTopupOrder = initSysUserTopupOrder(dtsUserDB.getId(), dtsUser.getBalance());
                        userTopupOrder.setShopId(shopId);
                        userTopupOrder.setRemark(dtsUser.getRemake());
                        userTopupOrders.add(userTopupOrder);
                        continue;
                    }
                }
            }
            //账单表
            dtsUserBillService.saveBatch(dtsUserBills);
            //充值表
            userTopupOrderService.saveBatch(userTopupOrders);
            log.info("【用户充值】{}", JSON.toJSONString(insertDtsUsers, true));
            dtsUserService.updateBatchById(insertDtsUsers);
            cantMatch.removeAll(match);
        }
        return cantMatch;
    }


    /****
     * 初始化充值表
     * @param userId
     * @param balance
     * @return
     */
    private SysUserTopupOrder initSysUserTopupOrder(Long userId, BigDecimal balance) {
        SysUserTopupOrder userTopupOrder = new SysUserTopupOrder();
        userTopupOrder.setId(IdWorker.getId());
        userTopupOrder.setUserId(userId);
        userTopupOrder.setAmount(balance);
        userTopupOrder.setType((byte) 2);
        userTopupOrder.setStatus((byte) 2);
        userTopupOrder.setCreated(new Date());
        userTopupOrder.setReviewTime(new Date());
        userTopupOrder.setModifyBy(SecurityUtils.getUserId());
        return userTopupOrder;
    }


    /**
     * 初始化账单表
     *
     * @param userId
     * @param balance
     * @return
     */
    private DtsUserBill initDtsUserBill(Long userId, BigDecimal balance, Byte status, String remark) {
        DtsUserBill dtsUserBill = new DtsUserBill();
        dtsUserBill.setId(IdWorker.getId());
        dtsUserBill.setUserId(userId);
        dtsUserBill.setStatus(status);
        dtsUserBill.setAmount(balance);
        dtsUserBill.setType((byte) 2);
        dtsUserBill.setCreated(new Date());
        dtsUserBill.setRemark(remark);
        return dtsUserBill;
    }


    /***
     * 系统充值
     * @param userId
     * @param amount
     * @return
     */
    public boolean systemRecharge(Long userId, BigDecimal amount, Byte status, String remark, Long shopId) {
        log.info("【系统充值】：用户ID：{} ,金额：{}", userId, amount);
        DtsUserBill dtsUserBill = initDtsUserBill(userId, amount, status, remark);
        SysUserTopupOrder userTopupOrder = initSysUserTopupOrder(userId, amount);
        userTopupOrder.setRemark(remark);
        userTopupOrder.setShopId(shopId);
        DtsUser dtsUser = dtsUserService.getById(userId);
        if (dtsUser == null) {
            throw new MyException("系统充值失败，用户ID无效");
        }
        DtsUser inisDtsUser = new DtsUser();
        inisDtsUser.setId(userId);
        inisDtsUser.setBalance(dtsUser.getBalance().add(amount));
        //账单表
        dtsUserBillService.save(dtsUserBill);
        //充值表
        userTopupOrderService.save(userTopupOrder);
        return dtsUserService.updateById(inisDtsUser);
    }


    /***
     * 修改押金
     * @param id
     * @param amount
     * @return
     */
    public boolean systemRecharge1(Long id, BigDecimal amount) {
        log.info("【后台修改押金】：操作人ID：{} ,金额：{}", SecurityUtils.getUserId(), amount);
        try {
            //租车信息
            DtsCarRental dtsCarRental = dtsCarRentalService.getById(id);
            //修改用户租车押金
            DtsCarRental carRental = new DtsCarRental();
            carRental.setId(id);
            carRental.setDeposit(amount);
            dtsCarRentalService.updateById(carRental);
            //修改用户信息押金
            DtsUser dtsUser = dtsUserService.getById(dtsCarRental.getUserId());
            dtsUser.setDeposit(amount);
            dtsUserService.updateById(dtsUser);
            return true;
        } catch (Exception e) {
            log.error("【后台修改押金错误， msg】：{}", e.getMessage());
            return false;
        }
    }
}
